﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Tiger.Models;
using System.Web.Mvc;
using System.Diagnostics;

namespace Tiger.Common
{
    public class FilePreviewUtil
    {
        // 附件转换列表
        private static List<string> UndergoingAttachList = new List<string>();

        /// <summary>
        /// 附件ID
        /// </summary>
        /// <param name="AttId"></param>
        /// <param name="FilePath"></param>
        public static object PreviewFile(string AttId, string FilePath)
        {
            // 检测是否正在生成
            if(UndergoingAttachList.Contains(AttId))
            {
                return new JsonNetResult(new
                {
                    Status = 0,
                    Message = "任务处理中..."
                });
            }
            else
            {
                // 附件导出目录
                string PreviewExportFolder = System.Configuration.ConfigurationManager.AppSettings["PreviewExportFolder"];

                Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(FilePath);

                Aspose.Cells.Rendering.ImageOrPrintOptions imgOptions = new Aspose.Cells.Rendering.ImageOrPrintOptions();
                imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                imgOptions.OnePagePerSheet = true;

                var guid = Guid.NewGuid().ToString();
                UndergoingAttachList.Add(AttId);
                for (int i = 0; i < wb.Worksheets.Count; i++)
                {
                    Aspose.Cells.Worksheet sheet = wb.Worksheets[i];

                    Aspose.Cells.Rendering.SheetRender sr = new Aspose.Cells.Rendering.SheetRender(sheet, imgOptions);

                    var FinalPath = string.Format(@"{0}\{1}\{2}.jpg", PreviewExportFolder, guid, i);
                    if (!Directory.Exists(Path.Combine(PreviewExportFolder, guid)))
                    {
                        Directory.CreateDirectory(Path.Combine(PreviewExportFolder, guid));
                    }

                    sr.ToImage(0, FinalPath);
                }

                // 写入数据库
                using (WhDbContext whdb = new WhDbContext())
                {
                    TGR_AttachPreview NewAttachPreview = new TGR_AttachPreview();
                    NewAttachPreview.AttachID = AttId;
                    NewAttachPreview.PageCount = wb.Worksheets.Count;
                    NewAttachPreview.PreviewID = guid;

                    whdb.AttachPreview.Add(NewAttachPreview);
                    whdb.SaveChanges();
                }

                UndergoingAttachList.Remove(AttId);

                return new JsonNetResult(new
                {
                    Status = 1,
                    PageCount = wb.Worksheets.Count,
                    PreviewID = guid
                });
            }
        }

        /// <summary>
        /// 预览CEB
        /// </summary>
        /// <param name="AttId"></param>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static object PreviewCeb(string AttId, string FilePath)
        {
            try
            {
                // 检测是否正在生成
                if (UndergoingAttachList.Contains(AttId))
                {
                    return new JsonNetResult(new
                    {
                        Status = 0,
                        Message = "任务处理中..."
                    });
                }
                else
                {
                    UndergoingAttachList.Add(AttId);
                    var guid = Guid.NewGuid().ToString();
                    // 附件导出目录
                    string PreviewExportFolder = System.Configuration.ConfigurationManager.AppSettings["PreviewExportFolder"];

                    if (!Directory.Exists(Path.Combine(PreviewExportFolder, guid)))
                    {
                        Directory.CreateDirectory(Path.Combine(PreviewExportFolder, guid));
                    }
                    // 获得Ceb2Pdf路径
                    string Ceb2PdfExe = System.Configuration.ConfigurationManager.AppSettings["Ceb2PdfExe"];
                    string Ceb2PdfFolder = System.Configuration.ConfigurationManager.AppSettings["Ceb2PdfFolder"];

                    // 复制CEB文件，加上.CEB后缀
                    var newFilePath = FilePath + ".ceb";
                    if(!File.Exists(newFilePath))
                    {
                        File.Copy(FilePath, newFilePath);
                    }
                    // 转换CEB成PDF
                    Process p = Process.Start("\"" + Ceb2PdfExe + "\"", string.Format(" \"{0}\"", newFilePath));
                    p.WaitForExit();
                    // 移动转换好的文件到Cache目录
                    var TargetPath = Path.Combine(PreviewExportFolder, Path.Combine(guid, "0.pdf"));
                    if(!File.Exists(TargetPath))
                    {
                        File.Move(FilePath+".pdf", TargetPath);
                    }
                    // 写入数据库
                    using (WhDbContext whdb = new WhDbContext())
                    {
                        TGR_AttachPreview NewAttachPreview = new TGR_AttachPreview();
                        NewAttachPreview.AttachID = AttId;
                        NewAttachPreview.PageCount = 1;
                        NewAttachPreview.PreviewID = guid;

                        whdb.AttachPreview.Add(NewAttachPreview);
                        whdb.SaveChanges();
                    }
                    UndergoingAttachList.Remove(AttId);
                    return new JsonNetResult(new
                    {
                        Status = 1,
                        PreviewID = guid
                    });
                }
            }
            catch(Exception e)
            {
                UndergoingAttachList.Remove(AttId);
                return new JsonNetResult(new
                {
                    Status = -1,
                    Message = e.Message
                });
            }
        }
    }
}